<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Load visualizations via a webmap</title>
<style>
  html,
  body,
  #viewDiv {
    padding: 0;
    margin: 0;
    height: 100%;
    width: 100%;
  }
</style>

<link rel="stylesheet" href="https://js.arcgis.com/4.2/esri/css/main.css">
<script src="https://js.arcgis.com/4.2/"></script>

<script>
  require([
    "esri/WebMap",
    "esri/views/MapView",
    "esri/widgets/Legend",
    "esri/widgets/LayerList",
    "esri/layers/GroupLayer",
    "dojo/domReady!"
  ], function(WebMap, MapView, Legend, LayerList, GroupLayer) {

    // Reference the id of the webmap item from AGO

    var map = new WebMap({
      portalItem: {
        id: "e2f9fa54ac5b4573bd09ba82f3208f7f"
      }
    });

    // point to the webmap instance in the view

    var view = new MapView({
      container: "viewDiv",
      map: map
    });

    // The view calls load() on the webmap and draws the layers
    // in the view. We'll grab the operational layers and create a
    // GroupLayer with them so the user can exclusively toggle their
    // visibility with the LayerList widget

    view.then(function(){
      var legend = new Legend({
        view: view
      });
      var layerList = new LayerList({
        view: view
      });

      view.ui.add(legend, "bottom-left");
      view.ui.add(layerList, "top-right");

      return view.map.layers;
    }).then(createGroupLayer)
      .otherwise(function(error){
        console.log("error: ", error);
      });

    // Creates a GroupLayer with the given layers and
    // adds it to the map while removing the other layers
    // from the map

    function createGroupLayer(layers){
      var groupLayer = new GroupLayer({
        visibilityMode: "exclusive",
        layers: layers,
        title: view.map.portalItem.title
      });
      view.map.removeAll();
      view.map.add(groupLayer);
      return groupLayer;
    }

  });
</script>
</head>

<body>
  <div id="viewDiv"></div>
</body>
</html>